- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path460. LFU Cache.go
74 lines (68 loc) · 1.61 KB
/
460. LFU Cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package leetcode
import"container/list"
typeLFUCachestruct {
nodesmap[int]*list.Element
listsmap[int]*list.List
capacityint
minint
}
typenodestruct {
keyint
valueint
frequencyint
}
funcConstructor(capacityint) LFUCache {
returnLFUCache{nodes: make(map[int]*list.Element),
lists: make(map[int]*list.List),
capacity: capacity,
min: 0,
}
}
func (this*LFUCache) Get(keyint) int {
value, ok:=this.nodes[key]
if!ok {
return-1
}
currentNode:=value.Value.(*node)
this.lists[currentNode.frequency].Remove(value)
currentNode.frequency++
if_, ok:=this.lists[currentNode.frequency]; !ok {
this.lists[currentNode.frequency] =list.New()
}
newList:=this.lists[currentNode.frequency]
newNode:=newList.PushBack(currentNode)
this.nodes[key] =newNode
ifcurrentNode.frequency-1==this.min&&this.lists[currentNode.frequency-1].Len() ==0 {
this.min++
}
returncurrentNode.value
}
func (this*LFUCache) Put(keyint, valueint) {
ifthis.capacity==0 {
return
}
ifcurrentValue, ok:=this.nodes[key]; ok {
currentNode:=currentValue.Value.(*node)
currentNode.value=value
this.Get(key)
return
}
ifthis.capacity==len(this.nodes) {
currentList:=this.lists[this.min]
frontNode:=currentList.Front()
delete(this.nodes, frontNode.Value.(*node).key)
currentList.Remove(frontNode)
}
this.min=1
currentNode:=&node{
key: key,
value: value,
frequency: 1,
}
if_, ok:=this.lists[1]; !ok {
this.lists[1] =list.New()
}
newList:=this.lists[1]
newNode:=newList.PushBack(currentNode)
this.nodes[key] =newNode
}